import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:syria_sports/presentation/login_screen/login_screen.dart';
import 'package:syria_sports/presentation/players/player_profile_screen/player_profile_screen.dart';
import 'package:syria_sports/presentation/settings_page/settings_screen.dart';
import '../../../data/remote/database_helper.dart';
import '../../../data/remote/launcher_url_in_platform.dart';

import '../../../dialogs/add_complaints_dialog.dart';
import '../../../dialogs/art_dialog.dart';
import '../../about_us_page/about_us_screen.dart';
import '../../gyms_admins/add_gym_admin_page/bloc/add_admin_page_screen.dart';
import '../../gyms_admins/add_subscription_requests_page/bloc/add_subscription_requests_screen.dart';
import '../../players/add_player_page/widgets/my_circle_avatar.dart';
import '../../dashboard_container_screen/dashboard_container_screen.dart';
import '../../gyms/public_gyms_page/bloc/gyms_screen.dart';
import '../../my_qr_code/bloc/my_qr_code_screen.dart';
import '../../coaches/public_coaches_page/bloc/public_coaches_tab_screen.dart';
import '../../players/public_players_page/bloc/public_players_screen.dart';
import '../widgets/ad_widget.dart';
import '../widgets/drawer_button.dart';
import '../widgets/public_home_button.dart';
import 'public_home_cubit.dart';
import 'package:flutter/material.dart';

class PublicHomeScreen extends StatelessWidget {
  const PublicHomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    Locale currentLocale = Localizations.localeOf(context);
    String formattedDate;
    String formattedTime;

    try {
      formattedDate = DateFormat('EEEE, d MMMM', currentLocale.languageCode)
          .format(DateTime.now());
      formattedTime = DateFormat('HH:mm', currentLocale.languageCode)
          .format(DateTime.now());
    } catch (e) {
      formattedDate = DateFormat('EEEE, d MMMM').format(DateTime.now());
      formattedTime = DateFormat('HH:mm, d MMMM').format(DateTime.now());
    }

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(ImageConstant.imgBackground),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        appBar: AppBar(
          title: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('اهلا بك في النادي', style: theme.textTheme.titleSmall),
              Text(formattedDate, style: theme.textTheme.bodySmall),
            ],
          ),
          actions: [
            InkWell(
              onTap: () {
                if (PrefUtils.isLogged()) {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => MyQrCodeScreen(
                                code: PrefUtils.getBarcode(),
                              )));
                } else {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => LoginScreen()));
                }
              },
              child: CustomImageView(
                margin: const EdgeInsets.all(4),
                height: 100,
                fit: BoxFit.fitHeight,
                imagePath: ImageConstant.imgLogo,
              ),
            ),
          ],
        ),
        drawer: Drawer(
          backgroundColor: Theme.of(context).colorScheme.secondary,
          child: Column(
            children: [
              Expanded(
                child: ListView(
                  children: [
                    const SizedBox(
                      height: 64,
                    ),
                    if (PrefUtils.isLogged())
                      Hero(
                        tag: "player_selected-1",
                        child: MyCircleAvatar(
                          borderColor: Colors.red,
                          backgroundColor:
                              Theme.of(context).colorScheme.onPrimaryContainer,
                          width: 45,
                          padding: const EdgeInsets.all(8),
                          editMode: false,
                          imageURL: PrefUtils.getImageLink(),
                        ),
                      )
                    else
                      MyCircleAvatar(
                        borderColor: Colors.red,
                        backgroundColor:
                            Theme.of(context).colorScheme.onPrimaryContainer,
                        width: 45,
                        padding: const EdgeInsets.all(8),
                        editMode: false,
                        imagePath: ImageConstant.icLogo,
                      ),
                    Align(
                      alignment: Alignment.center,
                      child: Text(
                        PrefUtils.getFullName(),
                        style: theme.textTheme.titleMedium!
                            .copyWith(color: Colors.deepOrange),
                      ),
                    ),
                    if (PrefUtils.isLogged() && !PrefUtils.isCoach())
                      MyDrawerButton(
                        icon: Icons.person,
                        onTapped: () {
                          Navigator.pop(context);
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      PlayerProfileScreen.builder(
                                          context: context, index: -1)));
                        },
                        title: 'ملف اللاعب',
                      ),
                    if (PrefUtils.isCoach())
                      MyDrawerButton(
                        icon: Icons.admin_panel_settings_outlined,
                        onTapped: () {
                          Navigator.pop(context);
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      DashboardContainerScreen.builder(
                                          context)));
                        },
                        title: 'الإدارة',
                      ),
                    if (!PrefUtils.isLogged())
                      MyDrawerButton(
                        icon: Icons.login,
                        onTapped: () {
                          Navigator.pop(context);
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => LoginScreen()));
                        },
                        title: 'تسجيل دخول',
                      ),

                    /*MyDrawerButton(
                      icon: Icons.sports_kabaddi_outlined,
                      onTapped: (){
                        Navigator.push(context, MaterialPageRoute(builder: (context) => const PublicGymsScreen()));
                      },
                      title: 'النوادي',
                    ),*/
                    if (!PrefUtils.isLogged())
                      MyDrawerButton(
                        icon: Icons.airplane_ticket_outlined,
                        onTapped: () {
                          Navigator.pop(context);
                          launchSocialMediaAppIfInstalled(
                              url: AppConstant.whatsappLink);
                          //Navigator.push(context, MaterialPageRoute(builder: (context) => const AddSubscriptionRequestsScreen()));
                          //Navigator.push(context, MaterialPageRoute(builder: (context) => const AddGymAdminPageScreen()));
                        },
                        title: 'انضم الينا',
                      ),
                    MyDrawerButton(
                      icon: Icons.settings,
                      onTapped: () {
                        Navigator.pop(context);
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const SettingsScreen()));
                      },
                      title: 'الاعدادات',
                    ),
                    if (PrefUtils.isLogged())
                      MyDrawerButton(
                        icon: Icons.support_agent_outlined,
                        onTapped: () {
                          Navigator.pop(context);
                          showDialog(
                              context: context,
                              builder: (context) {
                                return const AddComplaintDialog();
                              });
                        },
                        title: 'الابلاغ عن مشكلة',
                      ),
                    MyDrawerButton(
                      icon: Icons.privacy_tip_outlined,
                      onTapped: () {
                        Navigator.pop(context);
                        launchInBrowser(Uri.parse(
                            'https://www.freeprivacypolicy.com/live/0fb0dee3-7034-4c46-b92f-2172705f7d53'));
                      },
                      title: 'سياسة الخصوصية',
                    ),
                    /*MyDrawerButton(
                      icon: Icons.favorite,
                      onTapped: (){
                        Navigator.push(context, MaterialPageRoute(builder: (context) => const BannerExample()));
                      },
                      title: 'شاهد اعلان لدعمنا',
                    ),*/
                    MyDrawerButton(
                      icon: Icons.info_outline,
                      onTapped: () {
                        Navigator.pop(context);
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const AboutUsScreen()));
                      },
                      title: 'من نحن',
                    ),
                    if (PrefUtils.isLogged())
                      MyDrawerButton(
                        onTapped: () async {
                          var res = await AlertDialogs.yesCancelDialog(
                              context,
                              'تأكيد تسجيل الخروج',
                              'سيتم حذف جميع البيانات لمخزنة مؤقتا في هذا الجهاز');

                          if (res == DialogsAction.yes) {
                            var darkMode = PrefUtils.getThemeData();
                            PrefUtils.clearPreferencesData();
                            await DatabaseHelper.clearAllTables().then((value) {
                              Navigator.of(context, rootNavigator: true)
                                  .pushReplacement(
                                MaterialPageRoute(
                                  builder: (context) =>
                                      const PublicHomeScreen(),
                                ),
                              );
                              ThemeBloc themeCubit = BlocProvider.of(context);
                              themeCubit
                                  .add(ThemeChangeEvent(themeType: darkMode));
                            }).catchError((error) {
                              Navigator.of(context, rootNavigator: true)
                                  .pushReplacement(
                                MaterialPageRoute(
                                  builder: (context) =>
                                      const PublicHomeScreen(),
                                ),
                              );
                              ThemeBloc themeCubit = BlocProvider.of(context);
                              themeCubit
                                  .add(ThemeChangeEvent(themeType: darkMode));
                            });
                          }
                        },
                        icon: Icons.logout,
                        title: 'تسجيل خروج',
                      ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextButton(
                  onPressed: () {
                    launchInBrowser(Uri.parse('https://mustafaateyfor.com/'));
                    Navigator.pop(context);
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text('Developer info',
                          style: theme.textTheme.titleMedium),
                      Padding(
                        padding: const EdgeInsets.only(bottom: 2.0),
                        child: Image.asset(
                          ImageConstant.icBackground,
                          width: 40,
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        body: BlocProvider<PublicHomeCubit>(
          create: (context) => PublicHomeCubit()..init(),
          child: BlocConsumer<PublicHomeCubit, PublicHomeState>(
            listener: (context, state) {
              // TODO: implement listener
            },
            builder: (context, state) {
              var cubit = PublicHomeCubit.get(context);

              return SizedBox(
                height: height,
                width: width,
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      PublicHomeButton(
                        image: ImageConstant.imgGyms,
                        title: 'النوادي',
                        subtitle: 'أماكن التدريب والمواعيد والأسعار',
                        description: 'تصفح قائمة النوادي',
                        onTapped: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      const PublicGymsScreen()));
                        },
                      ),
                      /*PublicHomeButton(
                        image: ImageConstant.imgCoaches,
                        title: 'الكوادر',
                        subtitle: 'تعرف على كوادر الأكاديمية',
                        description: 'شاهد قائمة من افضل المدربين',
                        onTapped: (){
                          Navigator.push(context, MaterialPageRoute(builder: (context) => const PublicCoachesTabScreen()));
                        },
                      ),*/
                      PublicHomeButton(
                        image: ImageConstant.imgPlayers,
                        title: 'TOP 20',
                        subtitle: '',
                        description: 'شاهد أفضل 20 لاعب',
                        onTapped: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      const PublicPlayersScreen()));
                        },
                      ),
                      Align(
                        alignment: Alignment.centerRight,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                              vertical: 8.0, horizontal: 8),
                          child: Text('تابعنا على:',
                              style: theme.textTheme.titleLarge),
                        ),
                      ),
                      SizedBox(
                        height: 64 + 8,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 55),
                          child: Wrap(
                            alignment: WrapAlignment.center,
                            children: [
                              for (int i = 0; i < cubit.links.length; i++)
                                IconButton(
                                  onPressed: () {
                                    launchSocialMediaAppIfInstalled(
                                        url: cubit.links[i].link);
                                  },
                                  icon: Image.asset(cubit.links[i].icon,
                                      width: 32),
                                ),
                            ],
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(4.0),
                        child: TextButton(
                          onPressed: () {
                            launchInBrowser(
                                Uri.parse('https://mustafaateyfor.com/'));
                          },
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Text(
                                'Developer info',
                                style: theme.textTheme.titleMedium,
                              ),
                              Padding(
                                padding: const EdgeInsets.only(bottom: 2.0),
                                child: Image.asset(
                                  ImageConstant.icBackground,
                                  width: 40,
                                ),
                              )
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}

/*




                    if(PrefUtils.isLogged())
                            InkWell(
                              onTap: (){
                                Navigator.push(context, MaterialPageRoute(builder: (context) => PlayerProfileScreen.builder(context: context)));
                              },
                              child: Column(
                                children: [
                                  SizedBox(
                                      height: 100,
                                      child: Center(child: Image.asset(ImageConstant.icMyProfile))),
                                  Padding(
                                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                    child: Text('ملف اللاعب',
                                        style: theme.textTheme.titleLarge),
                                  ),
                                ],
                              ),
                            )
                          else
                            InkWell(
                              onTap: (){
                                Navigator.push(context, MaterialPageRoute(builder: (context) => LoginScreen()));
                              },
                              child: Column(
                                children: [
                                  SizedBox(
                                      height: 100,
                                      child: Center(child: Image.asset(ImageConstant.icJoinNow))),
                                  Padding(
                                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                    child: Text('انضم الينا',
                                        style: theme.textTheme.titleLarge),
                                  ),
                                ],
                              ),
                            ),

                          InkWell(
                            onTap: (){
                               Navigator.push(context, MaterialPageRoute(builder: (context) => const LinksScreen(isPublic: true,)));
                            },
                            child: Column(
                              children: [
                                SizedBox(
                                    height: 100,
                                    child: Center(child: Image.asset(ImageConstant.icSocialMedia))),
                                Padding(
                                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                  child: Text('تابعنا',
                                      style: theme.textTheme.titleLarge),
                                ),
                              ],
                            ),
                          ),
                    Container(
                                color: Colors.white12,
                                child: SizedBox(
                                  height: 190,
                                  child: ListView.builder(
                                    itemCount: cubit.publicHomeData.gyms.length,
                                      scrollDirection: Axis.horizontal,
                                      itemBuilder: (context,index){
                                    return GymItemView(gym: cubit.publicHomeData.gyms[index],);
                                  }),
                                ),
                              ),
                              const SizedBox(
                                height: 4,
                              ),
                              // top coaches
                              Align(
                                alignment: Alignment.centerRight,
                                child: Padding(
                                  padding: const EdgeInsets.symmetric(horizontal: 8),
                                  child: Text('افضل المدربين:',
                                      style: theme.textTheme.titleLarge),
                                ),
                              ),
                              SizedBox(
                                height: 150,
                                child: ListView.builder(
                                    itemCount: cubit.publicHomeData.topCoaches.length,
                                    scrollDirection: Axis.horizontal,
                                    itemBuilder: (context,index){
                                      return PublicCoachItemView(user: cubit.publicHomeData.topCoaches[index],);
                                    }),
                              ),

                              const SizedBox(
                                height: 4,
                              ),
                              // top player
                              Align(
                                alignment: Alignment.centerRight,
                                child: Padding(
                                  padding: const EdgeInsets.symmetric(horizontal: 8),
                                  child: Text('افضل اللاعبين:',
                                      style: theme.textTheme.titleLarge),
                                ),
                              ),
                              Container(
                                color: Colors.white12,
                                child: SizedBox(
                                  height: 120,
                                  child: ListView.builder(
                                      itemCount: cubit.publicHomeData.topPlayers.length,
                                      scrollDirection: Axis.horizontal,
                                      itemBuilder: (context,index){
                                        return PublicPlayerItemView(user: cubit.publicHomeData.topPlayers[index],);
                                      }),
                                ),
                              ),

                              */
